package ru.spbu.math.seabattle.client.jms.gui;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;

import ru.spbu.math.seabattle.client.jms.SeaBattleClient;
import ru.spbu.math.seabattle.entity.TurnResult;

public class SeaBattleGUI extends JFrame {

	private static final long serialVersionUID = 1L;

	private ExtendedContainer content = new ExtendedContainer(this
			.getContentPane());
	private FieldComponent playerField;
	private FieldComponent enemyField;

	public SeaBattleGUI(final SeaBattleClient client, String playerName) {

		super("(" + playerName + ")" + " This is SEA-BATTLE!!!");
		playerField = new FieldComponent(client);
		enemyField = new FieldComponent(client);
		this.setBounds(Constants.getFrameRectangle());
		this.setResizable(false);

		content.setLayout(null);

		playerField.setBounds(Constants.getPlayerFieldRectangle());
		content.add(playerField);

		enemyField.setBounds(Constants.getEnemyFieldRectangle());
		enemyField.disableAll();
		content.add(enemyField);
		
		this.addWindowListener(new WindowListener() {

			@Override
			public void windowClosing(WindowEvent arg0) {
				client.sayGoodbyeToYourServer();
			}

			@Override public void windowActivated(WindowEvent arg0) {}
			@Override public void windowClosed(WindowEvent arg0) {}
			@Override public void windowDeactivated(WindowEvent arg0) {}
			@Override public void windowDeiconified(WindowEvent arg0) {}
			@Override public void windowIconified(WindowEvent arg0) {}
			@Override public void windowOpened(WindowEvent arg0) {}
		});
	}

	public void startPlacingShips() {

		playerField.placeShip();
	}

	public void startTurn() {

		enemyField.addListenersToEnemy();
	}

	public void shootEnemy(TurnResult result) {

		System.out.println("SEA-BATTLE_GUI: SHOOT-ENEMY: " + result.i + " " + result.j);
		if (result.success) {
			enemyField.setColor(result.i, result.j, Constants.getDamagedShipColor());
			enemyField.setDemagedShip(result.i, result.j);
		} else {
			enemyField.setColor(result.i, result.j, Constants.getShotCellColor());
			enemyField.setShotCell(result.i, result.j);
		}
	}
	
	public void shootPlayer(TurnResult result) {

		if (result.success)
			playerField.setColor(result.i, result.j, Constants.getDamagedShipColor());
		else
			playerField.setColor(result.i, result.j, Constants.getShotCellColor());
	}
	
	public void waitForTurn() {
		enemyField.removeEnemyListeners();
	}
}
